<?php

class NodeController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('node');
        
        $activeResource=$this->getRequest()->getControllerName();
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Node'));
        
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    /**
     * Nodes default listing action
     * Latest nodes by type and category
     *
     */
    public function indexAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
        
        $nodeTbl=new Application_Model_NodeDb();
        
        $list=array();
        
        $types=Application_Model_NodeTypes::getValidTypes();
        $categories=Application_Model_NodeCategories::getValidCategories();
        
        foreach ($types as $type)
        {
            foreach ($categories as $category)
            {
                list($nodes,$paginator)=$nodeTbl->getNodesPageByTypeAndCategory($type,$category,1,5,true);
                $list=array_merge($list,$nodes);
            }
        }
        
        $this->view->nodes=$list;
    }
    
    /**
     * Front page nodes listing action
     *
     */
    public function frontAction()
    {
        if (!Zend_Registry::get('user')->canView(new Application_Model_UserResources(Application_Model_UserResources::getFrontResource())))
        {
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
        
        $key=(int) $this->_getParam('key');
        
        $nodeTbl=new Application_Model_NodeDb();
        
        list($nodes,$paginator)=$nodeTbl->getFrontNodesPage($key,5,true);
        
        $this->view->nodes=$nodes;
        $this->view->paginator=$paginator;
    }
    
     /**
     * Nodes listing by type action
     *
     */
    public function typeAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $type=(string) $this->_getParam('type');
        $key=(int) $this->_getParam('key');
        
        $nodeTbl=new Application_Model_NodeDb();
        
        list($nodes,$paginator)=$nodeTbl->getNodesPageByType($type,$key,1,true);
        
        $this->view->nodes=$nodes;
        $this->view->paginator=$paginator;
    }
    
    /**
     * Nodes listing by category action
     *
     */
    public function categoryAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $category=(string) $this->_getParam('category');
        $key=(int) $this->_getParam('key');
        
        $nodeTbl=new Application_Model_NodeDb();
        
        list($nodes,$paginator)=$nodeTbl->getNodesPageByCategory($category,$key,5,true);
        
        $this->view->nodes=$nodes;
        $this->view->paginator=$paginator;
    }
    
    /**
     * Nodes listing by URL alias action
     *
     */
    public function viewAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $alias=(string) $this->_getParam('alias');
        
        $nodeTbl=new Application_Model_NodeDb();
        
        $nodes=$nodeTbl->fetchNodesByAlias($alias,true);
        $authors=array();
        
        $userTbl=new Application_Model_UserDb();
        
        $first=true;
        foreach ($nodes as $nodeObj)
        {
            $userObj=$userTbl->fetchUserById($nodeObj->uid);
            
            $authors[$nodeObj->uid]=$userObj;
            
            if ($first)
                $this->view->headTitle()->set($nodeObj->title);
            else 
                $this->view->headTitle()->append($nodeObj->title);
                
            $this->view->headMeta()->appendName('keywords', $nodeObj->getKeywords())
                                   ->appendName('description', $nodeObj->getDescription());
        }
        
        $this->view->nodes=$nodes;
        $this->view->authors=$authors;
    }

    /**
     * Node adding action
     *
     */
    public function addAction()
    {
        if (!Zend_Registry::get('user')->canPost())
        {
            return $this->_helper->redirector('index');
        }
        
        Zend_Registry::get('layout')->setLayout('duty');
        Zend_Registry::get('view')->jQuery()->uiEnable();
        
        $form=new Application_Form_Node();
        
        $request=$this->getRequest();
        
        if ($request->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                $node=array(
                    'title' => $form->getValue('title'),
                    'short_text' => $form->getValue('short_text'),
                    'full_text' => ini_get('magic_quotes_gpc') ? stripslashes($form->getValue('full_text')) : $form->getValue('full_text'),
                    'publish_date' => preg_replace('/([\d]{2})\/([\d]{2})\/([\d]{4})/','$3-$2-$1',$form->getValue('publish_date')),
                    'published' => $form->getValue('published'),
                    'front' => $form->getValue('front'),
                    'uid' => Zend_Registry::get('user')->id,
                    'type' => $form->getValue('type'),
                    'category' => $form->getValue('category'),
                    'url_alias' => $form->getValue('url_alias'),
                    'language' => $form->getValue('language'),
                    'meta' => array(
                                'keywords' => $form->getValue('keywords'),
                                'description' => $form->getValue('description'),
                                'thumbnail_filename' => '',
                                'thumbnail_ext' => ''
                              )
                );
                
                //creating thumbnail
                if (!empty($node['full_text']) && preg_match('/<img[^>]+src[\x20]*[=][\x20]*[\x22]('.addcslashes($this->view->siteUrl(),'/').')?(.+?)[\x22][^>]*>/si',$node['full_text'],$matches))
                {
                    $img_url=trim($matches[2],'/');
                    
                    if (file_exists(ROOT_DIR.'/'.$img_url))
                    {
                        if (preg_match('/^data\/uploads\/([^\.]+?)\.(.+?)$/',$img_url,$img_match))
                        {
                            $node['meta']['thumbnail_filename']=$img_match[1];
                            $node['meta']['thumbnail_ext']=$img_match[2];
                        }
                    }
                }
        
                
                $nodeObj=new Application_Model_Node($node);
                
                $nodeTbl=new Application_Model_NodeDb();
                $nid=$nodeTbl->save($nodeObj);
                
                // creating tags
                if (!empty($nid))
                {
                    $tagsTbl=new Application_Model_TagsDb();

                    $keywords=$nodeObj->getKeywords();
                    if (!empty($keywords))
                    {
                        $tags=explode(',',$keywords);
                        
                        foreach($tags as $tag)
                        {
                            $tagObj=new Application_Model_Tags(array(
                                                                'tag' => trim($tag),
                                                                'nid' => $nid,
                                                                'url_alias' => $node['url_alias'],
                                                                'language' => $node['language']
                                                                ));
                            
                            $tagsTbl->save($tagObj);
                        }
                    }
                }
                
                //clearing cache
                $cache=Zend_Registry::get('cache');
                $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
                
                $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Node saved'));
             //   return $this->_helper->redirector('index');
                return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('node/list'));
            }
            
            $this->view->message=Zend_Registry::get('locale')->_('Node not saved');
        }
        
        $this->view->form=$form;
        
        $this->view->tinyMCE();
    }
    
    /**
     * Node editing action
     *
     */
    public function editAction()
    {
        $key=$this->_getParam('key');
        
        if (empty($key) || !Zend_Registry::get('user')->canManage())
        {
            return $this->_helper->redirector('index');
        }

        $nodeTbl=new Application_Model_NodeDb();
        
        $node=$nodeTbl->fetchNodeById($key);
        
        if (!$node->isExists())
        {
            return $this->_helper->redirector('index');
        }
        
        Zend_Registry::get('layout')->setLayout('duty');
        Zend_Registry::get('view')->jQuery()->uiEnable();
        
        $form=new Application_Form_Node($node);
        
        $request=$this->getRequest();
        
        if ($request->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                $node->title=$form->getValue('title');
                $node->short_text=$form->getValue('short_text');
                $node->full_text=ini_get('magic_quotes_gpc') ? stripslashes($form->getValue('full_text')) : $form->getValue('full_text');
                $node->publish_date = preg_replace('/([\d]{2})\/([\d]{2})\/([\d]{4})/','$3-$2-$1',$form->getValue('publish_date'));
                $node->published = $form->getValue('published');
                $node->front = $form->getValue('front');
                $node->uid = Zend_Registry::get('user')->id;
                $node->type = $form->getValue('type');
                $node->category = $form->getValue('category');
                $node->url_alias = $form->getValue('url_alias');
                $node->language = $form->getValue('language');
                $node->setKeywords($form->getValue('keywords'));
                $node->setDescription($form->getValue('description'));
                
                //creating thumbnail
                if (!empty($node->full_text) && preg_match('/<img[^>]+src[\x20]*[=][\x20]*[\x22]('.addcslashes($this->view->siteUrl(),'/').')?(.+?)[\x22][^>]*>/si',$node->full_text,$matches))
                {
                    $img_url=trim($matches[2],'/');
                    
                    if (file_exists(ROOT_DIR.'/'.$img_url))
                    {
                        if (preg_match('/^data\/uploads\/([^\.]+?)\.(.+?)$/',$img_url,$img_match))
                        {
                            $node->setThumbnail($img_match[1],$img_match[2]);
                        }
                    }
                }

                $nodeTbl->save($node);
                
                // creating tags
                $tagsTbl=new Application_Model_TagsDb();
                
                $tagsTbl->deleteByNid($node->id);
                
                $keywords=$node->getKeywords();
                if (!empty($keywords))
                {
                    $tags=explode(',',$keywords);
                    
                    foreach($tags as $tag)
                    {
                        $tagObj=new Application_Model_Tags(array(
                                                            'tag' => trim($tag),
                                                            'nid' => $node->id,
                                                            'url_alias' => $node->url_alias,
                                                            'language' => $node->language
                                                            ));
                        
                        $tagsTbl->save($tagObj);
                    }
                }
                
                //clearing cache
                $cache=Zend_Registry::get('cache');
                $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
                
                $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Node saved'));
             //   return $this->_helper->redirector('index');
                return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('node/list'));
            }
            
            $this->view->message=Zend_Registry::get('locale')->_('Node not saved');
        }
        
        $this->view->form=$form;
        
        $this->view->tinyMCE();
    }
    
    /**
     * Node view by ID action
     *
     */
    public function idAction()
    {
        $user=Zend_Registry::get('user');
        
        if (!$user->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $key=(int) $this->_getParam('key');
        
        if (empty($key))
        {
            return $this->_helper->redirector('index');
        }
        
        $nodeTbl=new Application_Model_NodeDb();
        $nodeObj=$nodeTbl->fetchNodeById($key);

        if (!$nodeObj->isExists() || (!$nodeObj->isPublished() && !$user->canManage()))
        {
            return $this->_helper->redirector('index');
        }
        
        $userTbl=new Application_Model_UserDb();
        $userObj=$userTbl->fetchUserById($nodeObj->uid);
        
        $this->view->publish_date=$nodeObj->publish_date;
        $this->view->title=$nodeObj->title;
        $this->view->node=$nodeObj;
        $this->view->author=$userObj;
        
        $this->view->headTitle()->set($nodeObj->title);
        $this->view->headMeta()->appendName('keywords', $nodeObj->getKeywords())
                               ->appendName('description', $nodeObj->getDescription());
    }
    
    /**
     * Nodes list action
     *
     */
    public function listAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_helper->redirector('index');
        }
        
        $key=(int) $this->_getParam('key');
        
        $nodeTbl=new Application_Model_NodeDb();

        if (Zend_Registry::get('user')->canManage())
        {
            list($nodes,$paginator)=$nodeTbl->getNodesPage($key,5);
        } else 
        {
            list($nodes,$paginator)=$nodeTbl->getNodesPage($key,5,true);
        }
        
        $this->view->nodes=$nodes;
        $this->view->paginator=$paginator;
    }
    
    /**
     * Node delete action
     *
     */
    public function deleteAction()
    {
        $key=(int) $this->_getParam('key');
        
        if (empty($key) || !Zend_Registry::get('user')->canManage())
        {
            return $this->_helper->redirector('index');
        }
        
        $nodeTbl=new Application_Model_NodeDb();
        $node=$nodeTbl->fetchNodeById($key);
        
        if (!$node->isExists())
        {
            return $this->_helper->redirector('index');
        }

        $nodeTbl->delete($node);
        
        //clearing cache
        $cache=Zend_Registry::get('cache');
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
        
        $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Node was deleted'));
     //   return $this->_helper->redirector('list');
        return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('node/list'));
    }
}

